package u1.Server;


import u1.common.User;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;
import java.util.*;


public class LocalUserCache implements Serializable {
    private static List<User> userList = new ArrayList<>();

    static {
        readUser();
    }

    // 添加用户

    public static boolean addUser(User user) {
        User user2 = userList.stream().filter(user1 -> user1.equals(user)).findFirst().orElse(null);
        if (user2 == null) {
            userList.add(user);
            saveUser(userList);
            return true;
        }
        return false;
    }

    //验证通过
    public static boolean loginAccount(User user) {
        User user2 = userList.stream().filter(user1 -> user1.getPassword().equals(user.getPassword())).findFirst().orElse(null);
        if (user2 == null) {
            return false;
        }
        return true;
    }



    // 存储用户数据

    public static boolean saveUser(List<User> userList){
        XMLEncoder encoder = null;
        try {
            encoder = new XMLEncoder(new FileOutputStream("F:\\Java高级1\\novelRead\\src\\novelRead\\xnovelSave\\users.xml"));
            encoder.writeObject(userList);
            encoder.flush();
            encoder.close();
            return true;
        } catch (Exception e) {
            //throw new RuntimeException(e);
            return false;
        }
    }

    // 删除指定对象

    public static boolean deleteUser(User user) {
        User user2 = userList.stream().filter(user1 -> user1.equals(user)).findFirst().orElse(null);
        if (user2 == null) {
            return false;
        }
        userList.remove(user);
        return true;
    }

    //读取用户数据

    public static boolean readUser(){
        XMLDecoder decoder = null;
        try {
            decoder = new XMLDecoder(new FileInputStream("F:\\Java高级1\\novelRead\\src\\novelRead\\xnovelSave\\users.xml"));
            userList = (ArrayList) decoder.readObject();
            return true;
        } catch (Exception e) {
            System.out.println("不存在xml文件路径，重新初始中");
            saveUser(userList);
            return false;
        }
    }
}
